from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse,JsonResponse
import json

# Create your views here.

def reverse_demo(request):
    print(reverse('request_response:index'))

    return redirect(reverse('users:index'))

# GET  /jsonResponse_demo/
def jsonResponse_demo(request):
    # json_data = {
    #     "name": "cg",
    #     "age": 18
    # }
    json_list_data = [1, 2, 3]  # json数据更喜欢顶层括号是 {}
    # return JsonResponse(json_data, safe=False)
    return JsonResponse({'list':json_list_data})

def weather1(request, year,city):
    print(request.user)
    print(city)
    print(year)
    return HttpResponse('---weather1-----')


def weather2(request, city, year):

    print(city)
    print(year)
    return HttpResponse('weather2')

# GET /response_demo/
def response_demo(request):

    # return HttpResponse(content='hello', content_type='text/plain', status=201)
    return HttpResponse(content='hello', content_type='text/html', status=201)


# 演示获取查询参数 ?a=10&b=20&a=30
# request.GET  它是一个属性用来获取查询参数 得到QueryDict
# QueryDict 类型对象 get()方法可以获取一键一值  getlist()方法获取一键多值
def get_query_param(requset):
    a = requset.GET.get('a')
    b = requset.GET.get('b')
    alist = requset.GET.getlist('b')
    print(a)
    print(b)
    print(alist)

    return HttpResponse('get_query_param')

# 演示获取请求体中的表单数据
# request.POST 属性用来获取请求体中的表单数据 也是得到一个QueryDict类型的对象
def get_body_form(request):
    a = request.POST.get('a')
    like = request.POST.getlist('like')

    return HttpResponse('get_body_form')

#获取请求体中非表单数据,请求方式是POST请求，数据在请求体中携带。
def get_body_json(request):
    json_str_bytes = request.body
    json_str = json_str_bytes.decode()


    dict1 = json.loads(json_str)

    return HttpResponse('get_body_json')

def cookie_demo(request):
    #演示cookie读写操作
    # response.set_cookie(cookie名，value=cookie值，max_age=cookie有效期)
    response = HttpResponse('cookie_demo')#创建相应对象
    response.set_cookie('name','ss',max_age=3600)
    print(request.COOKIES.get('name'))
    # response.delete_cookie('name')  #删除cookie值
    return response


def session_demo(request):
    #演示session操作
    request.session['name'] = 'dd'

    print(request.session.get('name'))
    return HttpResponse('session_demo')
